package com.wlm.blogs.service;

import com.wlm.blogs.NotFoundException;
import com.wlm.blogs.dao.TypeRepository;
import com.wlm.blogs.po.Type;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service
public class TypeServiceImpl implements TypeService
{
    @Autowired
    private TypeRepository typeRepository;

    @Transactional
    @Override
    public Type saveType(Type type)
    {
        return typeRepository.save(type);
    }

    @Transactional
    @Override
    public Type getType(Long id)
    {
        Type type=typeRepository.findById(id).get();
        return type;
    }

    @Transactional
    @Override
    public Page<Type> listType(Pageable pageable)
    {
        return typeRepository.findAll(pageable);
    }

    @Transactional
    @Override
    public Type updateType(Long id,Type type)
    {
        Type t=typeRepository.findById(id).get();
        if(t==null)
        {
            throw new NotFoundException("不存在该类型");
        }
        BeanUtils.copyProperties(t,type);
        return typeRepository.save(t);
    }

    @Transactional
    @Override
    public void deleteType(Long id)
    {
    typeRepository.deleteById(id);
    }

    @Override
    public Type getTypeByName(String name) {
        return typeRepository.findByName(name);
    }

    @Override
    public List<Type> listType() {
        return typeRepository.findAll();
    }
}
